#/bin/bash

###########################################################################
#
#    Script that configures and installs Squid with SSL Bump
#    Copyright (C) 2020 AidanVPN
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/
#
###########################################################################

#############################
############VARS#############
#############################

# Script Name
MyScriptName='AidanVPN-Squid SSLBump'

# Get Machine IP Address
function ip_address(){
  local IP="$( ip addr | egrep -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | egrep -v "^192\.168|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-2]\.|^10\.|^127\.|^255\.|^0\." | head -n 1 )"
  [ -z "${IP}" ] && IP="$( wget -qO- -t1 -T2 ipv4.icanhazip.com )"
  [ -z "${IP}" ] && IP="$( wget -qO- -t1 -T2 ipinfo.io/ip )"
  [ ! -z "${IP}" ] && echo "${IP}" || echo
} 
IPADDR="$(ip_address)"

# Server local time
MyVPS_Time='Asia/Kuala_Lumpur'
#############################

function InstDependencies(){
echo "Checking if you are root..."

if [ "$(whoami)" != "root" ]
then
	echo "Need root privileges to run this script."
	exit 1
else
	echo "You are root, perfect!"
fi

apt-get update && apt-get upgrade

echo "Checking for Squid duplicate installation..."
sleep 2

if [ "$(dpkg --list | grep 'squid')" != "" ]
then
        echo "Squid is currently installed! Removing squid..."
		apt-get remove --purge squid
else
	echo "No duplicate Squid installation...."
fi

echo "Installing Squid dependencies..."
sleep 2

apt-get install g++ gcc make libgnutls28-dev libcap2-bin libdbi-perl libssl-dev libecap3 -y
}

function InstSquidSSL(){
echo "Fetching squid source from the internet and unpacking data..."
sleep 2

# CD to opt and download squid 4.6
cd /opt/
wget http://www.squid-cache.org/Versions/v4/squid-4.6.tar.gz

# Decompress Squid 4.6 package
tar -zxvf squid-4.6.tar.gz
cd squid-4.6

# Configule SSL on Squid 4.6 package
./configure --prefix=/usr --localstatedir=/var --libexecdir=/usr/lib/squid --datadir=/usr/share/squid --sysconfdir=/etc/squid --enable-ssl-crtd --with-openssl --enable-translation --enable-cpu-profiling --disable-dependency-tracking -enable-delay-pools --with-default-user=proxy --with-logdir=/var/log/squid --with-pidfile=/var/run/squid.pid

# Make Package
make
make install

}

function InstDir(){
# Create the necessary directories for squid to work and assign access rights for them
mkdir -p /var/log/squid
mkdir -p /etc/squid/ssl
chown proxy:proxy /var/log/squid
chown proxy:proxy /etc/squid/ssl
chmod 700 /var/log/squid
chmod 700 /etc/squid/ssl
}

function InstService(){
# Remove duplicate service
rm -rf /etc/init.d/squid

# Create custom Squid Service
cat <<'SquidService' > /etc/init.d/squid
#! /bin/sh
#
# squid		Startup script for the SQUID HTTP proxy-cache.
#
# Version:	@(#)squid.rc  1.0  07-Jul-2006  luigi@debian.org
#
# pidfile: /var/run/squid.pid
#
### BEGIN INIT INFO
# Provides:          squid
# Required-Start:    $network $remote_fs $syslog
# Required-Stop:     $network $remote_fs $syslog
# Should-Start:      $named
# Should-Stop:       $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Squid HTTP Proxy version 4.x
### END INIT INFO
 
NAME=squid
DESC="Squid HTTP Proxy"
DAEMON=/usr/sbin/squid
PIDFILE=/var/run/$NAME.pid
CONFIG=/etc/squid/squid.conf
SQUID_ARGS="-YC -f $CONFIG"
 
[ ! -f /etc/default/squid ] || . /etc/default/squid
 
. /lib/lsb/init-functions
 
PATH=/bin:/usr/bin:/sbin:/usr/sbin
 
[ -x $DAEMON ] || exit 0
 
ulimit -n 65535
 
find_cache_dir () {
	w=" 	" # space tab
        res=`$DAEMON -k parse -f $CONFIG 2>&1 |
		grep "Processing:" |
		sed s/.*Processing:\ // |
		sed -ne '
			s/^['"$w"']*'$1'['"$w"']\+[^'"$w"']\+['"$w"']\+\([^'"$w"']\+\).*$/\1/p;
			t end;
			d;
			:end q'`
        [ -n "$res" ] || res=$2
        echo "$res"
}
 
grepconf () {
	w=" 	" # space tab
        res=`$DAEMON -k parse -f $CONFIG 2>&1 |
		grep "Processing:" |
		sed s/.*Processing:\ // |
		sed -ne '
			s/^['"$w"']*'$1'['"$w"']\+\([^'"$w"']\+\).*$/\1/p;
			t end;
			d;
			:end q'`
	[ -n "$res" ] || res=$2
	echo "$res"
}
 
create_run_dir () {
	run_dir=/var/run/squid
	usr=`grepconf cache_effective_user proxy`
	grp=`grepconf cache_effective_group proxy`
 
	if [ "$(dpkg-statoverride --list $run_dir)" = "" ] &&
	   [ ! -e $run_dir ] ; then
		mkdir -p $run_dir
	  	chown $usr:$grp $run_dir
		[ -x /sbin/restorecon ] && restorecon $run_dir
	fi
}
 
start () {
	cache_dir=`find_cache_dir cache_dir`
	cache_type=`grepconf cache_dir`
	run_dir=/var/run/squid
 
	#
	# Create run dir (needed for several workers on SMP)
	#
	create_run_dir
 
	#
	# Create spool dirs if they don't exist.
	#
	if test -d "$cache_dir" -a ! -d "$cache_dir/00"
	then
		log_warning_msg "Creating $DESC cache structure"
		$DAEMON -z -f $CONFIG
		[ -x /sbin/restorecon ] && restorecon -R $cache_dir
	fi
 
	umask 027
	ulimit -n 65535
	cd $run_dir
	start-stop-daemon --quiet --start \
		--pidfile $PIDFILE \
		--exec $DAEMON -- $SQUID_ARGS < /dev/null
	return $?
}
 
stop () {
	PID=`cat $PIDFILE 2>/dev/null`
	start-stop-daemon --stop --quiet --pidfile $PIDFILE --exec $DAEMON
	#
	#	Now we have to wait until squid has _really_ stopped.
	#
	sleep 2
	if test -n "$PID" && kill -0 $PID 2>/dev/null
	then
		log_action_begin_msg " Waiting"
		cnt=0
		while kill -0 $PID 2>/dev/null
		do
			cnt=`expr $cnt + 1`
			if [ $cnt -gt 24 ]
			then
				log_action_end_msg 1
				return 1
			fi
			sleep 5
			log_action_cont_msg ""
		done
		log_action_end_msg 0
		return 0
	else
		return 0
	fi
}
 
cfg_pidfile=`grepconf pid_filename`
if test "${cfg_pidfile:-none}" != "none" -a "$cfg_pidfile" != "$PIDFILE"
then
	log_warning_msg "squid.conf pid_filename overrides init script"
	PIDFILE="$cfg_pidfile"
fi
 
case "$1" in
    start)
	res=`$DAEMON -k parse -f $CONFIG 2>&1 | grep -o "FATAL: .*"`
	if test -n "$res";
	then
		log_failure_msg "$res"
		exit 3
	else
		log_daemon_msg "Starting $DESC" "$NAME"
		if start ; then
			log_end_msg $?
		else
			log_end_msg $?
		fi
	fi
	;;
    stop)
	log_daemon_msg "Stopping $DESC" "$NAME"
	if stop ; then
		log_end_msg $?
	else
		log_end_msg $?
	fi
	;;
    reload|force-reload)
	res=`$DAEMON -k parse -f $CONFIG 2>&1 | grep -o "FATAL: .*"`
	if test -n "$res";
	then
		log_failure_msg "$res"
		exit 3
	else
		log_action_msg "Reloading $DESC configuration files"
	  	start-stop-daemon --stop --signal 1 \
			--pidfile $PIDFILE --quiet --exec $DAEMON
		log_action_end_msg 0
	fi
	;;
    restart)
	res=`$DAEMON -k parse -f $CONFIG 2>&1 | grep -o "FATAL: .*"`
	if test -n "$res";
	then
		log_failure_msg "$res"
		exit 3
	else
		log_daemon_msg "Restarting $DESC" "$NAME"
		stop
		if start ; then
			log_end_msg $?
		else
			log_end_msg $?
		fi
	fi
	;;
    status)
	status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit 3
	;;
    *)
	echo "Usage: /etc/init.d/$NAME {start|stop|reload|force-reload|restart|status}"
	exit 3
	;;
esac
 
exit 0
SquidService

# Make the script executable and add it to autoload
chmod +x /etc/init.d/squid
update-rc.d squid defaults

# Create certificate for Squid
echo "Creating self-signed certificate for Squid..."
sleep 2
mkdir /etc/squid/ssl_cert
cd /etc/squid/ssl_cert
openssl req -new -newkey rsa:2048 -days 365 -nodes -x509 -subj "/C=MY/ST=selangor/L=Gombak/O=AidanVPN/CN=aidan.my" -keyout squid.key  -out squid.crt
chown -R proxy:proxy .
chmod -R 700 .
}

function ScriptMessage(){
 echo -e " [\e[1;32m$MyScriptName VPS Installer\e[0m]"
 echo -e ""
 echo -e "(｡◕‿◕｡) Script by AidanVPN"
 echo -e ""
}

function InstConfig(){
# Remove Duplicate Squid config
rm -rf /etc/squid/squid.conf

# Create SSL Config
cat << EOF > /etc/squid/squid.conf
# My Squid Proxy Server Config
acl VPN dst IP-ADDRESS/32
acl step1 at_step SslBump1
ssl_bump peek step1
ssl_bump bump all
http_access allow VPN
http_access deny all 
http_port 3355
http_port 8085 intercept
http_port 85 intercept ssl-bump generate-host-certificates=on dynamic_cert_mem_cache_size=4MB cert=/etc/squid/ssl_cert/squid.crt key=/etc/squid/ssl_cert/squid.key
### Allow Headers
request_header_access Allow allow all 
request_header_access Authorization allow all 
request_header_access WWW-Authenticate allow all 
request_header_access Proxy-Authorization allow all 
request_header_access Proxy-Authenticate allow all 
request_header_access Cache-Control allow all 
request_header_access Content-Encoding allow all 
request_header_access Content-Length allow all 
request_header_access Content-Type allow all 
request_header_access Date allow all 
request_header_access Expires allow all 
request_header_access Host allow all 
request_header_access If-Modified-Since allow all 
request_header_access Last-Modified allow all 
request_header_access Location allow all 
request_header_access Pragma allow all 
request_header_access Accept allow all 
request_header_access Accept-Charset allow all 
request_header_access Accept-Encoding allow all 
request_header_access Accept-Language allow all 
request_header_access Content-Language allow all 
request_header_access Mime-Version allow all 
request_header_access Retry-After allow all 
request_header_access Title allow all 
request_header_access Connection allow all 
request_header_access Proxy-Connection allow all 
request_header_access User-Agent allow all 
request_header_access Cookie allow all 
request_header_access All deny all
### HTTP Anonymizer Paranoid
reply_header_access Allow allow all 
reply_header_access Authorization allow all 
reply_header_access WWW-Authenticate allow all 
reply_header_access Proxy-Authorization allow all 
reply_header_access Proxy-Authenticate allow all 
reply_header_access Cache-Control allow all 
reply_header_access Content-Encoding allow all 
reply_header_access Content-Length allow all 
reply_header_access Content-Type allow all 
reply_header_access Date allow all 
reply_header_access Expires allow all 
reply_header_access Host allow all 
reply_header_access If-Modified-Since allow all 
reply_header_access Last-Modified allow all 
reply_header_access Location allow all 
reply_header_access Pragma allow all 
reply_header_access Accept allow all 
reply_header_access Accept-Charset allow all 
reply_header_access Accept-Encoding allow all 
reply_header_access Accept-Language allow all 
reply_header_access Content-Language allow all 
reply_header_access Mime-Version allow all 
reply_header_access Retry-After allow all 
reply_header_access Title allow all 
reply_header_access Connection allow all 
reply_header_access Proxy-Connection allow all 
reply_header_access User-Agent allow all 
reply_header_access Cookie allow all 
reply_header_access All deny all
### sslcrtd config
sslcrtd_program /usr/lib/squid/security_file_certgen -s /var/cache/squid/ssl_db -M 4MB
sslcrtd_children 5
### CoreDump
coredump_dir /var/spool/squid
dns_nameservers 8.8.8.8 8.8.4.4
refresh_pattern ^ftp: 1440 20% 10080
refresh_pattern ^gopher: 1440 0% 1440
refresh_pattern -i (/cgi-bin/|\?) 0 0% 0
refresh_pattern . 0 20% 4320
visible_hostname AidanVPN
EOF

# Setting machine's IP Address inside of our Squid config(security that only allows this machine to use this proxy server)
sed -i "s|IP-ADDRESS|$IPADDR|g" /etc/squid/squid.conf

# Calling Squid to create swap directories and initialize cert cache dir
if [ -d "/var/cache/squid/ssl_db" ]
then
	rm -rf /var/cache/squid/ssl_db
fi
/usr/lib/squid/security_file_certgen -c -s /var/cache/squid/ssl_db -M 1024
chown -R proxy:proxy /var/cache/squid/ssl_db

# Start Squid Service
service squid start
}



#############################################
#############################################
########## Installation Process##############
#############################################
## WARNING: Do not modify or edit anything
## if you did'nt know what to do.
## This part is too sensitive.
#############################################
#############################################

# First thing to do is check if this machine is Debian
 source /etc/os-release
if [[ "$ID" != 'debian' ]]; then
 ScriptMessage
 echo -e "[\e[1;31mError\e[0m] This script is for Debian only, exiting..." 
 exit 1
fi

# Begin Installation by Updating and Upgrading machine and then Installing all our wanted packages/services to be install.
ScriptMessage
sleep 2

# Configure Dependencies
echo -e "Configuring dependencies..."
InstDependencies

# Configure Squid 4.6 SSL
echo -e "Configuring Squid 4.6 SSL..."
InstSquidSSL

# Configure Directories
echo -e "Configuring Squid Directories..."
InstDir

# Configure Startup Service
echo -e "Configuring Startup Service..."
InstService

# Configure SSLBump CRTD
echo -e "Configuring SSLBump CRTD..."
InstConfig

ScriptMessage
sleep 3

echo " "
echo "Installation has been completed!!"
echo "--------------------------------------------------------------------------------"
echo "                          Debian Squid SSL Script                               "
echo "                               -AidanVPN-                                      "
echo "--------------------------------------------------------------------------------"
echo ""  | tee -a log-install.txt
echo "Maklumat Server"  | tee -a log-install.txt
echo "   - Squid SSLBump    : Port 85"  | tee -a log-install.txt
echo ""  | tee -a log-install.txt
echo " Copyright by (｡◕‿◕｡)AidanVPN"  | tee -a log-install.txt
echo ""  | tee -a log-install.txt
echo " Please Reboot your VPS"

# Clearing all logs from installation
rm -rf /root/.bash_history && history -c && echo '' > /var/log/syslog
